import type { PermissionRecord } from '@/DatabaseType/Permission';
import type { PermissionTreeNode } from '@/DatabaseType/User';
import type { RequestResult } from '@/utils/request';
import { ServiceProxy } from '@/constant';
import { request } from '@umijs/max';

// 获取权限树，并缓存请求，时间为1分钟
export async function getPermissionTree(): Promise<
  RequestResult<{
    permissionTree: PermissionTreeNode[];
    permissionList: PermissionRecord[];
  }>
> {
  return request(`${ServiceProxy.DefaultPrefix}/permission`, {
    method: 'GET',
    useCache: true,
    ttl: 60000, // 一分钟
    maxCache: 10,
  });
}

// 删除权限信息
export async function deletePermission(
  permissionId: number,
): Promise<RequestResult<void>> {
  return request(`${ServiceProxy.DefaultPrefix}/permission/${permissionId}`, {
    method: 'DELETE',
  });
}

// 新增权限信息
export async function addPermission(
  data: {
    parentId: number;
  } & Pick<
    PermissionRecord,
    'apiList' | 'name' | 'znName' | 'funcType' | 'pageUrl'
  >,
): Promise<RequestResult<number>> {
  return request(`${ServiceProxy.DefaultPrefix}/permission`, {
    method: 'POST',
    data: {
      ...data,
      type: '1',
    },
  });
}

// 更新权限信息
export async function updatePermission(
  permissionId: number,
  data: {
    parentId: number;
  } & Pick<
    PermissionRecord,
    'apiList' | 'name' | 'znName' | 'funcType' | 'pageUrl'
  >,
): Promise<RequestResult<number>> {
  return request(`${ServiceProxy.DefaultPrefix}/permission/${permissionId}`, {
    method: 'PUT',
    data,
  });
}
